<template>
  <div class="login-page">
    <div class="login-pic">
      <!-- <img src="../assets/imgs/bg/login1.png" alt="" /> -->
    </div>

    <div class="login-page-content">
      <div class="login-title-box">
        <div>
          <img :src="imgUrl" alt="" />
        </div>
        <h3>{{ config.site_name }}</h3>
      </div>
      <div class="login-section">
        <div class="section-left">
          <div class="section-left-content">
            <img :src="imgUrl" alt="" style="max-width: 250px;" />
            <!-- <div id="wx-qrcode"></div> -->
            <div class="top">
              <img src="../assets/imgs/icon/icon1.png" alt="" />
              <span>扫一扫登录</span>
            </div>
            <div class="memo">
              请打开
              <span @click="openWx">企业微信</span>
              扫码登陆
            </div>
          </div>
        </div>
        <div class="section-right">
          <div class="section-right-content">
            <el-tabs v-model="activeName" class="demo-tabs">
              <el-tab-pane label="账号登录" :name="1">
                <div>
                  <el-form :model="formData" :rules="rules" ref="ruleFormRef">
                    <el-form-item prop="username">
                      <el-input v-model="formData.username" placeholder="请输入用户名" :prefix-icon="User" />
                    </el-form-item>
                    <el-form-item prop="password">
                      <el-input v-model="formData.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" />
                    </el-form-item>
                    <el-form-item prop="captcha">
                      <div class="login-captcha">
                        <el-input class="captcha-input" v-model="formData.captcha" placeholder="请输入验证码"
                          :prefix-icon="ChatLineSquare" />
                        <img id="captchaImg" @click="getVerifyApi" alt="" />
                      </div>
                    </el-form-item>
                    <el-form-item>
                      <div class="form-other">
                        <el-checkbox v-model="formData.checked" label="记住密码" size="large" />
                        <el-button type="primary" link>忘记密码？</el-button>
                      </div>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" style="width: 100%; height: 48px" @click="submit"
                        :loading="loading">登录</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-tab-pane>
              <el-tab-pane label="短信登录" :name="2">
                <el-form>
                  <el-form-item>
                    <el-input v-model="formData.phone" placeholder="请输入手机号" :prefix-icon="Iphone" />
                  </el-form-item>
                  <el-form-item>
                    <el-input v-model="formData.phCode" placeholder="请输入验证码" :prefix-icon="ChatLineSquare">
                      <template #suffix>
                        <el-button type="primary" link @click="getCode">获取验证码</el-button>
                      </template>
                    </el-input>
                  </el-form-item>

                  <el-form-item>
                    <div class="form-other">
                      <el-checkbox v-model="formData.checked" label="记住登录状态" size="large" />
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" style="width: 100%; height: 48px">登录</el-button>
                  </el-form-item>
                </el-form></el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { User, Lock, ChatLineSquare, Iphone } from "@element-plus/icons-vue";
import {
  loginApi,
  userApi,
  configApi,
  qyvxUrlApi,
  verificationApi,
} from "../plugins/api/login";
import { menusApi as listApi } from "@/plugins/api/system/menu";
import { useCounterStore } from "@/stores/counter.js";
import { addRouter } from "@/router/addRoutesFun";
import urlData from "@/assets/imgs/logo/logo.jpg";
const store = useCounterStore();
const router = useRouter();
const route = useRoute();
let activeName = ref(1);
let formData = ref({});
let rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};
// 图片验证码
function getVerifyApi() {
  let imgSrc = import.meta.env.VITE_APP_BASE_API + "/admin/login/verify";
  let date = new Date().getTime();
  let img = document.getElementById("captchaImg");
  img.src = imgSrc + "?time=" + date;
}
// 获取验证码
function getCode() {
  console.log(111);
}
let imgUrl = computed(() => {
  return store.configInfo.site_logo
    ? import.meta.env.VITE_APP_BASE_API + store.configInfo.site_logo
    : urlData;
});
// 登录
let ruleFormRef = ref(null);
let loading = ref(false);
function submit() {
  if (activeName.value == 1) {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        loading.value = true;
        setPw();
        loginApi({
          username: formData.value.username,
          password: formData.value.password,
          captcha: formData.value.captcha,
        })
          .then((data) => {
            localStorage.setItem("manpu_token", data.token);
            userApi()
              .then((info) => {
                localStorage.setItem("manpu_userInfo", JSON.stringify(info));
                store.userInfo = info;
                loading.value = false;
              })
              .catch(() => {
                loading.value = false;
              });
          })
          .then(() => {
            listApi().then((data) => {
              localStorage.setItem(
                "manpu_menuList",
                JSON.stringify(deepFilter(data))
              );

              addRouter(router, data);
              store.SET_MENU();
              ElMessage.success("登录成功！");
              //
              console.log(data);
              loading.value = false;
              //跳转
              if (data && data.length > 0) {
                let first = data[0]
                if (first.redirect) {
                  router.push(first.redirect);
                } else {
                  router.push(first.path);
                }
              }
            });
          })
          .catch(() => {
            getVerifyApi()
            loading.value = false;
          });
      }
    });
  }
}
//按键恢复
function keyDownReview() {
  document.onkeydown = function (event) {
    let e = event || window.event;
    if (e.keyCode === 13) {
      submit();
    }
  };
}
// 筛选数组
function deepFilter(list) {
  return list.filter((item) => {
    if (item.sub) {
      item.children = deepFilter(item.sub);
      delete item.sub;
    }
    return item;
  });
}
function changeArrData(arr) {
  if (!Array.isArray(arr)) return;
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (!item.sub) {
      delete item.sub;
      newArr.push(item);
    } else if (item.sub) {
      item.children = item.sub.map((ele) => {
        return ele;
      });
      newArr.push(item);
      // delete item.sub;
      changeArrData(item.children);
    }
  }
  return newArr;
}
// 记住密码
function setPw() {
  if (formData.value.checked) {
    let str = JSON.stringify(formData.value);
    localStorage.setItem("manpu_login", str);
  } else {
    localStorage.removeItem("manpu_login");
  }
}
function getPw() {
  let pw = localStorage.getItem("manpu_login");
  let obj = {};
  if (pw) {
    obj = JSON.parse(pw);
    formData.value.username = obj.username;
    formData.value.password = obj.password;
    formData.value.checked = obj.checked;
  }
}
let config = ref({});
function getConfigApi() {
  configApi({
    conf_name: "base.site_name",
  }).then((data) => {
    config.value = data.base;
    store.configInfo = data.base;
    localStorage.setItem("manpu_config", JSON.stringify(data.base));
    document.title = store.configInfo.site_name;
  });
}
// 企业微信
function getQyvxUrl() {
  qyvxUrlApi().then((data) => {
    console.log(data);
    window.location.href = data.url;
  });
}
let redirect_uri = ref(null);

function openWx() {
  getQyvxUrl();
}
// 企业微信应用回调地址，获取用户信息
function getWX_info(code) {
  loading.value = true;
  verificationApi(code)
    .then((data) => {
      localStorage.setItem("manpu_userInfo", JSON.stringify(data));
      store.userInfo = data;
      console.log("获取到用户信息：" + data);
      loading.value = false;
    })
    .then(() => {
      listApi().then((data) => {
        localStorage.setItem(
          "manpu_menuList",
          JSON.stringify(deepFilter(data))
        );

        addRouter(router, data);
        console.log("获取到菜单：" + data);
        store.SET_MENU();
        ElMessage.success("登录成功！");
        router.push("/");
        loading.value = false;
      });
    })
    .catch(() => {
      loading.value = false;
    });
}
onMounted(() => {
  // getQyvxUrl();
  getConfigApi();
  getPw();
  getVerifyApi();
  keyDownReview();
  console.log("页面初始化:" + route.query);
  if (route.query.code) {
    console.log("获取到code:" + route.query);
    getWX_info(route.query.code);
  }
});
onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>
<style lang="scss" scoped>
.login-page {
  width: 100%;
  height: 100vh;
  // background: #4889d7;

  display: flex;

  .login-pic {
    width: 45%;

    display: flex;
    flex-direction: column;
    justify-content: center;

    img {
      align-self: center;
      width: calc(100% - 40px);
      height: auto;
    }
  }

  .login-page-content {
    align-self: center;
    width: 50%;
    max-width: 794px;
    height: 550px;
    background: #ffffff;
    border-radius: 6px 6px 6px 6px;

    .login-title-box {
      width: 100%;
      height: 89px;
      background: #eff2f6;
      display: flex;

      >div {
        margin-left: 30px;
        text-align: center;
        font-size: 26px;
        align-self: center;

        img {
          width: 100%;
          height: auto;
          max-height: 50px;
          object-fit: cover;
          vertical-align: middle;
        }
      }

      h3 {
        margin: 0;
        margin-left: 10px;
        align-self: center;
        font-size: 24px;
        font-weight: bold;
        color: #252525;
        line-height: 22px;
      }
    }

    .login-section {
      width: 100%;
      height: calc(100% - 90px);
      display: flex;
      justify-content: space-between;

      >div {
        width: 50%;
        height: 100%;
      }

      .section-left {
        display: flex;
        justify-content: center;
        align-content: center;

        .section-left-content {
          text-align: center;
          align-self: center;

          #wx-qrcode {
            width: 200px;
            height: 200px;
            border: 1px solid black;
          }

          .top {
            img {
              width: 22px;
              height: auto;
              vertical-align: middle;
            }

            span {
              font-size: 20px;
              font-weight: 500;
              color: #172b4d;
              margin-left: 10px;
              vertical-align: middle;
            }
          }

          .memo {
            font-size: 16px;
            font-weight: 500;
            color: #5e6c84;
            line-height: 22px;
            margin-top: 10px;

            span {
              color: #00b2ff;
              user-select: none;
              cursor: pointer;
            }
          }

          .code {
            margin-top: 20px;
            width: 183px;
            height: 183px;
            border-radius: 0px 0px 0px 0px;
            border: 1px solid #f0f0f1;
            padding: 10px;
            box-sizing: border-box;

            img {
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .section-right {
        display: flex;
        flex-direction: column;
        justify-content: center;

        .section-right-content {
          width: 90%;

          .form-other {
            width: 100%;
            display: flex;
            justify-content: space-between;
          }

          .login-captcha {
            display: flex;
            justify-content: space-between;

            .captcha-input {
              width: calc(100% - 200px);
            }

            img {
              width: 150px;
              height: 50px;
              // object-fit: cover;
              cursor: pointer;
            }
          }
        }

        :deep(.el-input__wrapper) {
          height: 50px;
          border-radius: 0;
        }
      }
    }
  }
}
</style>
